package com.yczy365.petmall.controller;


import com.yczy365.petmall.ex.ServiceException;
import com.yczy365.petmall.web.JsonResult;
import com.yczy365.petmall.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
 * 全局异常处理器
 *
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult handleServiceException(ServiceException e){
      return JsonResult.fail(e);
    }

    @ExceptionHandler
    public JsonResult handleBindException(BindException e){
        //使用以下方式时,如果有多个检查错误
        //将获取其中某一个检查注解中配置的message值,但无法确定是哪一个
        String message=e.getFieldError().getDefaultMessage();
       return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,message);
        //使用以下方法时,如果有多个检查错误,将可以反馈所有的错误信息
       /* StringJoiner stringJoiner=new StringJoiner(", ","请求参数格式错误,","!");
        List<FieldError>fieldErrors=e.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            stringJoiner.add(fieldError.getDefaultMessage());
        }
        return stringJoiner.toString();*/
    }
   @ExceptionHandler
    public JsonResult handleConstraintViolationException(ConstraintViolationException e){
       Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
       String message = null;

       for (ConstraintViolation<?> constraintViolation : constraintViolations) {
           message=constraintViolation.getMessage();
       }
       return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,message);
   }
    @ExceptionHandler
    public JsonResult handleThrowable(Throwable e){
        log.warn("异常类型：",e.getClass().getName());
        log.warn("异常信息：",e.getMessage());
        log.warn("异常跟踪信息如下：",e);
        return JsonResult.fail(ServiceCode.ERR_UNKNOWN, "服务器忙，请稍后尝试，或联系系统管理员")
       ;
    }
}
